package book.controller;

import book.pojo.Book;
import book.pojo.DynamicParameter;
import book.pojo.PageBean;
import book.pojo.Reader;
import book.pojo.vo.ReaderVO;
import book.service.IBookService;
import book.service.IReaderService;
import book.service.impl.IBookServiceImpl;
import book.service.impl.IReaderServiceImpl;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.ResourceBundle;

@WebServlet({"/book","/book.do"})
public class BookController extends BaseController {
    private IBookService bookService = new IBookServiceImpl();

    //头像上传
    public void upload(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //加载minio.properties文件，读取配置信息
        ResourceBundle bundle = ResourceBundle.getBundle("minio");

        //获取配置
        String url = bundle.getString("minio.url");
        String accessKey = bundle.getString("minio.accessKey");
        String secretKey = bundle.getString("minio.secretKey");
        String bucketName = bundle.getString("minio.bucketName");

        //创建磁盘文件项工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //以factory对象为参，创建文件上传对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        //解析请求对象
        List<FileItem> list = upload.parseRequest(req);
        Book book = null;
        String avatarUrl =null;
        //遍历list
        for (FileItem item : list) {

            //如果不是普通表单项
            if(!item.isFormField()){
                //获取上传文件名称，拼接成物理路径--绝对路径
                String fileName = "D:\\dev_zy\\zy_worksapce\\javaweb\\BookManger2\\book_Cover\\"+item.getName();
                //构建minio客户端
                MinioClient client = MinioClient.builder().endpoint(url).credentials(accessKey,secretKey).build();
                //上传文件
                client.uploadObject(UploadObjectArgs.builder().bucket(bucketName)
                        .object(item.getName())
                        .filename(fileName)
                        .build());

                //将上传的头像路径存储到数据库中
                avatarUrl = item.getName();
            }else{
                String id = new String(item.get());
                //根据id查询用户
                book = bookService.findBookById(Integer.parseInt(id));
            }
        }
        //设置用户的头像
        book.setCover(avatarUrl);
        //更新用户
        bookService.updataBook(book);
        findAllBooks(req,resp);
    }
    // 显示所有图书
    public void findAllBooks(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        String id = req.getParameter("id");
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        String cover = req.getParameter("cover");

        PageBean<Book> pageBean = new PageBean<>();
        if(null != pageNo){
            pageBean.setPageNo(Integer.parseInt(pageNo));
        }
        if(null != pageSize){
            pageBean.setPageSize(Integer.parseInt(pageSize));
        }

        DynamicParameter parameter = new DynamicParameter("select * from books ");
        if(null != id && "" != id){
            parameter.addParam("id",id,"=");
        }
        if(null != title && "" != title){
            parameter.addParam("title",title,"like");
        }
        if(null != author && "" != author){
            parameter.addParam("author",author,"like");
        }
        //将查询参数添加到pageBean中
        pageBean.setParameter(parameter);

        //调用业务对象查询
        pageBean = bookService.findAllBooks(pageBean);

        //查总记录数
        int bookCount = bookService.getBookCount(pageBean);
        pageBean.setTotalCount(bookCount);

        //实现回显：将查询条件设置到请求域，传递回页面显示
        req.setAttribute("cover",cover);
        req.setAttribute("id",id);
        req.setAttribute("title",title);
        req.setAttribute("author",author);

        //将查询结果共享到请求域
        req.setAttribute("pageBean", pageBean);
        //转发到userList.jsp页面
        req.getRequestDispatcher("bookList.jsp").forward(req, resp);
    }

    // 处理添加请求
    public void addBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        String availableStr = req.getParameter("available");
        boolean available = Boolean.parseBoolean(availableStr);

        Book book = new Book();
        book.setTitle(title);
        book.setAuthor(author);
        book.setAvailable(available);

        int row = bookService.addBook(book);
        req.setAttribute("msg",row==1?"添加成功！":"添加失败！");
        // 获取表单数据并调用service
        this.findAllBooks(req,resp);
    }

    //根据id查询图书
    public void findBookById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Book book = bookService.findBookById(id);
        //将查询结果藏到请求域中
        req.setAttribute("book",book);
        System.out.println("controller中的findBookById: "+book);
        //转发到editUser.jsp
        req.getRequestDispatcher("editBook.jsp").forward(req,resp);
    }

    //更新图书
    public void updateBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int row = 0;
        String cover = req.getParameter("cover");
        int id = Integer.parseInt(req.getParameter("id"));
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        boolean available = req.getParameter("available") != null;

        Book book = new Book(id,title,author,cover,available);
        row = bookService.updataBook(book);

        req.setAttribute("msg",row==1?"更新成功！":"更新失败！");
        //查询
        this.findAllBooks(req,resp);
    }

    //删除图书
    public void deleteBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cover = req.getParameter("cover");
        int id = Integer.parseInt(req.getParameter("id"));
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        boolean available = req.getParameter("available") != null;

        Book book = new Book(id,title,author,cover,available);
        int row = bookService.deleteBook(book);

        req.setAttribute("msg",row==1?"更新成功！":"更新失败！");

        // 在 deleteBook 方法中
        resp.sendRedirect(req.getContextPath() + "/book?action=findAllBooks");
    }

    //用户登录

}